const createError = require('http-errors')
const express = require('express')
const path = require('path')
const cookieParser = require('cookie-parser')
const logger = require('morgan')
const cors = require('cors')

// const dataRouter = require('./fetch-data')
const homeRouter = require('./routes/home')
const sessionRouter = require('./routes/session')
const cartRouter = require('./routes/cart')
const addressRouter = require('./routes/address')
const tabsRouter = require('./routes/tabs')
const tabRouter = require('./routes/tab')
const detailRouter = require('./routes/detail')
const listRouter = require('./routes/list')
const suggestRouter = require('./routes/suggest')
const userRouter = require('./routes/user')
const orderRouter = require('./routes/order')
const searchRouter = require('./routes/search')

const mongoose = require('mongoose')
const { getUserInfo } = require('./utils/permission')
mongoose.connect('mongodb://localhost:27017/youxuan')

const app = express()

app.use(cors())

// view engine setup
app.set('views', path.join(__dirname, 'views'))
app.set('view engine', 'jade')

app.use(logger('dev'))
app.use(express.json())
app.use(express.urlencoded({ extended: false }))
app.use(cookieParser())
app.use(express.static(path.join(__dirname, 'public')))

const whitelist = ['/api/carts']
app.use((req, res, next) => {
  const { url, method } = req
  try {
    if (
      (url === '/api/sessions' &&
        (method.toUpperCase() === 'GET' ||
          method.toUpperCase() === 'DELETE')) ||
      whitelist.includes(url)
    ) {
      getUserInfo(req)
    }
    next()
  } catch (error) {
    res.json({
      code: 400,
      data: null,
      message: 'token认证失败',
    })
  }
})

app.use('/api/home', homeRouter)
app.use('/api/sessions', sessionRouter)
app.use('/api/carts', cartRouter)
app.use('/api/addresses', addressRouter)
app.use('/api/tabs', tabsRouter)
app.use('/api/tab', tabRouter)
app.use('/api/list', listRouter)
app.use('/api/detail', detailRouter)
app.use('/api/suggests', suggestRouter)
app.use('/api/users', userRouter)
app.use('/api/orders', orderRouter)
app.use('/api/search', searchRouter)

// app.use('/api/data', dataRouter)

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404))
})

// error handler
app.use(function (err, req, res, next) {
  // // set locals, only providing error in development
  // res.locals.message = err.message
  // res.locals.error = req.app.get('env') === 'development' ? err : {}

  // // render the error page
  // res.status(err.status || 500)
  // res.render('error')

  const tokenException = [
    'No token supplied',
    'Not enough or too many segments',
    'Algorithm not supported',
    'Signature verification failed',
    'Token not yet active',
    'Token expired',
    'Algorithm type not recognized',
  ]

  if (tokenException.includes(err.message)) {
    res.json({
      code: 400,
      data: null,
      message: 'token异常,请重新登录!',
    })
  } else {
    res.json({
      code: 400,
      data: null,
      message: err.message,
    })
  }
})

module.exports = app
